//
//  AppDelegate.m
//  Xspcf
//
//  Created by 小小算盘 on 16/1/22.
//  Copyright © 2016年 小小算盘. All rights reserved.
//


#import "AppDelegate.h"
#import "SunTabController.h"
#import "SunNavController.h"
#import "BeginOpenViewController.h"
#import "AppDelegate.h"
#import "SunStartVC.h"
#import "SunGesLoginVC.h"

#import "UMMobClick/MobClick.h"

#import <UMSocialCore/UMSocialCore.h>
//#import <ShareSDK/ShareSDK.h>
//#import <ShareSDKConnector/ShareSDKConnector.h>
//#import "WXApi.h"
#import "UMessage.h"
#import "TouchIDVC.h"
#import <AdSupport/AdSupport.h>
#import <LocalAuthentication/LocalAuthentication.h>
#import <UserNotifications/UserNotifications.h>

/********* new *******/


@interface AppDelegate ()<UNUserNotificationCenterDelegate>
{
    BOOL recome;
    
    
    int a;
    /********* new *******/
}
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent];
    if (!self.tab) {
        SunStartVC *vc = [[SunStartVC alloc]init];
        vc.time = 3;
        self.window.rootViewController = vc;
    }
    
    
     /*****************/
//    [[NSUserDefaults standardUserDefaults] setObject:@{@"MD5":@"df09f12079d8e0101bf51755c6fb4046",@"DES":@"b06fc3c7",@"AndAccessID":@"af1842798a1b6de9"} forKey:@"token"];
//    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"Real_Status"];
//    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:KLOGIN];
    /*****************/
    
    
    
    
//    BOOL isOpen = [[NSUserDefaults standardUserDefaults] boolForKey:kIsOpen];
//    if (!isOpen) {
//        self.window.rootViewController = [[BeginOpenViewController alloc]init];
//    }else{
//        //登录密码
//        LAContext* context = [[LAContext alloc] init];
//        if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:nil]&&[[NSUserDefaults standardUserDefaults]boolForKey:kusetouchid]) {
//            [self setTouchId];
//        }else if ([[NSUserDefaults standardUserDefaults] boolForKey:@"IsSetGesture"]) {
//            [self setLoginSecrit];
//        }else {
//            self.tab = [[SunTabController alloc]init];
//            self.window.rootViewController = self.tab;
//        }
//    }
    
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:KLOGIN]) {
    
    }else{
        [[NSUserDefaults standardUserDefaults] setObject:@{@"MD5":@"dsfdas213#@@$",@"DES":@"12345678",@"AndAccessID":@""} forKey:@"token"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    
    
    [self resignUmSDK];//注册友盟
    [self resignUmMessage:launchOptions];//友盟推送
    
    NSString *adid = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    NSLog(@"广告标示：%@",adid);
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [user setObject:adid forKey:@"ADID"];
    
    [user synchronize];
    return YES;
}

- (void)setTouchId{
    TouchIDVC *vc = [[TouchIDVC alloc]init];
    SunNavController *navigation = [[SunNavController alloc]initWithRootViewController:vc];
    self.window.rootViewController = navigation;
}

- (void)setLoginSecrit{
    SunGesLoginVC *gesture = [[SunGesLoginVC alloc]init];
    SunNavController *navigation = [[SunNavController alloc]initWithRootViewController:gesture];
    self.window.rootViewController = navigation;
}

- (void)resignUmMessage:(NSDictionary *)launchOptions{
    [UMessage startWithAppkey:@"5aa6230df43e4845c800007e" launchOptions:launchOptions];
    [UMessage registerForRemoteNotifications];
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate=self;
    UNAuthorizationOptions types10=UNAuthorizationOptionBadge|UNAuthorizationOptionAlert|UNAuthorizationOptionSound;
    [center requestAuthorizationWithOptions:types10 completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            //点击允许
            //这里可以添加一些自己的逻辑
        } else {
            //点击不允许
            //这里可以添加一些自己的逻辑
        }
    }];
    [UMessage setLogEnabled:YES];
}

//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于前台时的远程推送接受
        //关闭友盟自带的弹出框
        [UMessage setAutoAlert:NO];
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
    }else{
        //应用处于前台时的本地推送接受
    }
    //当应用处于前台时提示设置，需要哪个可以设置哪一个
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于后台时的远程推送接受
        //必须加这句代码
        NSString *urlStr = [userInfo objectForKey:@"url"];
        if (urlStr) {
            NSDictionary *param = [Sun dictionaryFromUrlString:urlStr];
            if (param) {
                id temp = [UIApplication sharedApplication].delegate;
                AppDelegate *delegate = temp;
                if (!delegate.tab) {
                    delegate.tab = [[SunTabController alloc]init];
                    delegate.window.rootViewController = delegate.tab;
                }
                [SunSupport shouldPushController:param];
            }
        }
        [UMessage didReceiveRemoteNotification:userInfo];
    }else{
        //应用处于后台时的本地推送接受
    }
}

- (void)resignUmSDK{
    UMConfigInstance.appKey = @"5aa6230df43e4845c800007e";
    [MobClick startWithConfigure:UMConfigInstance];
    
    
   
    //友盟分享
    [[UMSocialManager defaultManager] openLog:YES];
    [[UMSocialManager defaultManager] setUmSocialAppkey:@"5aa6230df43e4845c800007e"];
//    设置微信的appKey和appSecret
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatTimeLine appKey:@"wx80b8f9f7c47bb266" appSecret:@"9adf15d6a3f482a4c8368d2defd42285" redirectURL:@"https://m.xspcf.com"];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"100424468"  appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:@"3921700954"  appSecret:@"04b48b094faeb16683c32669824ebdad" redirectURL:@"http://sns.whalecloud.com/sina2/callback"];


}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        
    }
    return result;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
    
    }
    return result;
}

/*******ios 9 分享必须实现方法*******/
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(nonnull NSDictionary<NSString *,id> *)options{
    NSString *urlStr = [url absoluteString];
    NSDictionary *param = [Sun dictionaryFromUrlString:urlStr];
    if (param) {
        [SunSupport shouldPushController:param];
    }
    return [[UMSocialManager defaultManager] handleOpenURL:url];
}


-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"----------------%@",[[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                  stringByReplacingOccurrencesOfString: @">" withString: @""]
                 stringByReplacingOccurrencesOfString: @" " withString: @""]);
    NSString *str = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                     stringByReplacingOccurrencesOfString: @">" withString: @""]
                     stringByReplacingOccurrencesOfString: @" " withString: @""];
    [[NSUserDefaults standardUserDefaults]setObject:str forKey:@"DEVICE"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [UMessage didReceiveRemoteNotification:userInfo];
}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    completionHandler(UIBackgroundFetchResultNewData);
    NSString *urlStr = [userInfo objectForKey:@"url"];
    if (urlStr) {
        NSDictionary *param = [Sun dictionaryFromUrlString:urlStr];
        if (param) {
            id temp = [UIApplication sharedApplication].delegate;
            AppDelegate *delegate = temp;
            if (!delegate.tab) {
                delegate.tab = [[SunTabController alloc]init];
                delegate.window.rootViewController = delegate.tab;
            }
            [SunSupport shouldPushController:param];
        }
    }
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    NSDate *date=[NSDate dateWithTimeIntervalSinceNow:0];
    _beginDate=[date timeIntervalSince1970];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    NSDate * date=[NSDate dateWithTimeIntervalSinceNow:0];
    recome = YES;
    _endDate=[date timeIntervalSince1970];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"become" object:self];
    NSLog(@"回来了");
    [self compare];
    int timeInterval=_endDate-_beginDate;
    if (timeInterval >60 && recome) {
        recome = NO;
        //登录密码
        LAContext* context = [[LAContext alloc] init];
        if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:nil]&&[[NSUserDefaults standardUserDefaults]boolForKey:kusetouchid]) {
            [self setTouchId];
        }else if ([[NSUserDefaults standardUserDefaults] boolForKey:@"IsSetGesture"]) {
            [self setLoginSecrit];
        }
    }

}
-(void)compare
{
    if ([self compareVersionWithString:[[NSUserDefaults standardUserDefaults] objectForKey:@"VERSION"]]) {
        UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"由于您当前使用的版本功能相对较低，为了避免给您带来的麻烦，请更新至新版本" preferredStyle:UIAlertControllerStyleAlert];
        
        
        UIAlertAction *OK = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [self toJumpAppStore];
        }];
        [alertView addAction:OK];
        
        [self.window.rootViewController presentViewController:alertView animated:YES completion:nil];
        
    }
    
}

-(BOOL)compareVersionWithString:(NSString *)serverceVersion
{
    NSString *str = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    NSArray *currentVer = [str componentsSeparatedByString:@"."];
    NSArray *lowVer = [serverceVersion componentsSeparatedByString:@"."];
    if ([currentVer[0] intValue]>[lowVer[0] intValue]) {
        
        return NO;
    }
    else if ([currentVer[0] intValue]==[lowVer[0] intValue]){
        if ([currentVer[1] intValue]>[lowVer[1] intValue]) {
            return NO;
        }else if ([currentVer[1] intValue]==[lowVer[1] intValue]){
            if ([currentVer[2] intValue]>[lowVer[2] intValue]) {
                return NO;
            }else if ([currentVer[2] intValue]==[lowVer[2] intValue]){
                return NO;
            }else{
                return YES;
            }
        }else{
            return YES;
        }
    }
    else{
        return YES;
        
    }
    
    
}
//跳转App Store
-(void)toJumpAppStore
{
    NSString * str = @"https://itunes.apple.com/cn/app/xiao-suan-pan-cai-fu/id966769021?mt=8";
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark --new
/********* new *******/


@end
